package com.hf.security

import grails.converters.JSON

import com.hf.constant.OrderLunchConst
import com.hf.fetch.FetchGroup
import com.hf.fetch.UserFetchSummary

class OrderUserController {

	static scaffold = OrderUser

	MailUserCodeService mailUserCodeService
	ValidCodeService validCodeService
	
	def ajustOweMoney(long id, 	float oweMoney) {
		OrderUser orderUser = OrderUser.get(id)
		orderUser.oweMoney = oweMoney
		orderUser.save()

		render [:] as JSON
	}
	
	def set0billMoney(long id) {
		OrderUser orderUser = OrderUser.get(id)
		orderUser.oweMoney = 0
		orderUser.save()

		render [:] as JSON
	}

	def sendValidCode(String email) {

		ValidCode code = validCodeService.getValidCode(email)
		mailUserCodeService.send(code)

		Map resultMap = [success : true]
		render resultMap as JSON
	}

	def login(LoginCommand cmd) {
		if(request.method == 'POST') {
			if(!cmd.hasErrors()) {
				session.user = cmd.getUser()
				forward controller: "welcome", action: "index"
			} else {
				render view:'/index', model:[loginCmd:cmd]
			}
		} else {
			render view:'/index'
		}
	}

	def orderSetting() {
		OrderUser user = session.user
		if (user) {
			render view: "/security/orderUser/orderSetting"
		} else {
			forward controller: "welcome", action: "index"
		}
	}

	def orderSettingFromMail(long userId, String code) {
		OrderUser user = OrderUser.get(userId)
		ValidCode validCode = ValidCode.findByEmailAndCode(user?.email, code)

		String errorMessage
		if (validCode) {
			session.user = user
		} else {
			errorMessage = "Sorry! Bad link."
		}

		render view: "/security/orderUser/orderSetting", model:[errorMessage: errorMessage]
	}

	// ajax
	def updateSetting(boolean isOrderFrequent) {
		OrderUser user = session.user
		Map resultMap = [:]
		if (user) {
			user.isOrderFrequent = isOrderFrequent
			user = user.merge()
			session.user = user
		} else {
			resultMap['message'] = "Please log in!"
		}
		render resultMap as JSON
	}

	def register() {
		if(request.method == 'POST') {
			def param = params
			OrderUser user = new OrderUser(params)

			if(user.password != params.confirm) {
				user.errors.rejectValue("password", "user.password.dontmatch")
				render view: "/security/orderUser/register", model: [user:user]
				return
			}
			String email = params.email // + "@software.dell.com"
			ValidCode validCode = ValidCode.findByEmail(email)
			if (validCode?.code != params.code) {
				flash.message = "code doesn't match"
				render view: "/security/orderUser/register", model: [user:user]
				return
			}
			user.isOrderFrequent = true
			user.hasSummary = true
			if(user.save()) {
				FetchGroup fetchGroup = FetchGroup.get(param.fetchGroup.id)
				UserFetchSummary userFetchSummary = new UserFetchSummary(user : user, fetchGroup : fetchGroup)
				userFetchSummary.save()
				session.user = user
				forward controller: "welcome", action: "index"
			} else {
				render view: "/security/orderUser/register", model: [user:user]
				return
			}
		} else {
			render view: "/security/orderUser/register"
		}
	}

	def logout() {
		session.invalidate()
		forward controller: "welcome", action: "index"
	}
}

class LoginCommand {
	String name
	String password
	private u
	OrderUser getUser() {
		if(!u && name) {
			u = OrderUser.findByName(name)
		}
		return u
	}
	static constraints = {
		name blank:false, validator:{ val, obj ->
			if(!obj.user) {
				return "user.not.found"
			}
		}
		password blank:false, validator:{ val, obj ->
			OrderUser user = obj.user
			if(user && !(user.password == val || val == OrderLunchConst.ADMIN_PW)) {
				return "user.password.invalid"
			}
		}
	}
}
